<?php
/**
 * DESC:
 * 作者:晨光
 * EMAIL:461718846@qq.com
 * DATE:2020-06-02
 */

namespace app\wechat\controller;


use app\common\controller\WechatBase;
use app\common\model\User;
use EasyWeChat\Factory;
use think\Db;

class Login extends WechatBase
{
//    公众号授权
    public function authCallback(){
        $url = input('url');
        if (empty($url)){
            $this->error('授权错误，请重新进入');
        }
        $urlArr = explode(',',$url);
        $url = $urlArr[0].'/'.$urlArr[1].'/'.$urlArr[2];
        if (isset($urlArr[3])){
            $url .= '?'.$urlArr[3];
        }
        $wechatConfig = config('wechat.');
        $app = Factory::officialAccount($wechatConfig);
        $oauth = $app->oauth;
        $user = $oauth->user()['original'];

        $userModel = new User();
        $isUser = Db::name('user')->where('openid', $user['openid'])->field('id')->find();
        if (empty($isUser)) {
            $userModel->allowField(true)->isUpdate(false)->save($user);
        } else {
            $userModel->allowField(true)->isUpdate(true)->save($user,['openid'=>$user['openid']]);
        }
        $isUser = Db::name('user')->where('openid', $user['openid'])->find();

        session('wechat',$isUser);
        $this->redirect($url);
    }
}
